//
//  ImageSelectView.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/2.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "ImageSelectView.h"
#import "ImageSelectModel.h"
#import "BUIControl.h"

#define ScreenWidth  [UIScreen mainScreen].bounds.size.width

@interface ImageSelectView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>
@property (strong, nonatomic) UICollectionView *mainCollect;
@property (strong, nonatomic) UILongPressGestureRecognizer *longPressGr;
@end

@implementation ImageSelectView
@synthesize longPressGr;

static NSString *const cellID = @"cellId";

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self != nil ) {
        [self addSubview:self.mainCollect];
        [_mainCollect reloadData];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    self.backgroundColor = [UIColor redColor];
    if (self != nil) {
        self.autoresizesSubviews = YES;
        [self addSubview:self.mainCollect];
        _mainCollect.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
        [_mainCollect reloadData];
    }
    return self;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.arrDataSourc.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    for (int i = 0; i < cell.contentView.subviews.count; i++) {
        UIView *view = cell.contentView.subviews[i];
        [view removeFromSuperview];
    }
    ImageSelectModel *model = _arrDataSourc[indexPath.row];
    UIButton *btnSelect = [[UIButton alloc]initWithFrame:CGRectMake(10, 10, CGRectGetMaxX(cell.contentView.frame)-20, CGRectGetMaxX(cell.contentView.frame)-20)];
    [btnSelect setImage:model.imageShow forState:UIControlStateNormal];
    [btnSelect handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if (model.defaultItem == YES) {
            [self.delegate selectPhoto:^(UIImage *image) {
                ImageSelectModel *model = [[ImageSelectModel alloc] init];
                model.imageShow = image;
                model.defaultItem = NO;
                model.delectStart = NO;
                [_arrDataSourc insertObject:model atIndex:0];
                if (_arrDataSourc.count == 5) {
                    [_arrDataSourc removeObjectAtIndex:4];
                }
                [collectionView reloadData];
            }];
        }
    }];
    [cell.contentView addSubview:btnSelect];
    if (model.defaultItem != YES) {
        UIButton *btnDetal = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(btnSelect.frame)-40, -10, 40, 40)];
        btnDetal.tag = indexPath.row + 1;
        [btnDetal addTarget:self action:@selector(detailAction:) forControlEvents:UIControlEventTouchUpInside];
        [btnDetal setImage:[UIImage imageNamed:@"icon_delete"] forState:UIControlStateNormal];
        [btnDetal setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 20, 0)];
        [btnSelect addSubview:btnDetal];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate
//item宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){floor(self.frame.size.height),floor(self.frame.size.height)};}

//四周边间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0,0, 0,0);
}

//行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0f;
}

//列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.0f;
}

#pragma mark - set/get
- (UICollectionView *)mainCollect{
    if (_mainCollect == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置对齐方式
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //cell间距
        layout.minimumInteritemSpacing = 0.0f;
        //cell行距
        layout.minimumLineSpacing = 0.5f;
        _mainCollect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,CGRectGetMaxX(self.frame), self.frame.size.height) collectionViewLayout:layout];
        _mainCollect.backgroundColor = [UIColor greenColor];
        _mainCollect.delegate = self;
        _mainCollect.dataSource = self;
        [_mainCollect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellID];
        _mainCollect.backgroundColor = [UIColor whiteColor];
    }
    return _mainCollect;
}

- (NSMutableArray *)arrDataSourc{
    if (_arrDataSourc == nil) {
        _arrDataSourc = [NSMutableArray array];
        [self addDefaultModel];
    }
    return _arrDataSourc;
}

#pragma mark - 私有方法
- (void)addimageModel:(ImageSelectModel *)model{
    [_arrDataSourc insertObject:model atIndex:0];
    if (_arrDataSourc.count == 4) {
        [_arrDataSourc enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ImageSelectModel *model = obj;
            model.defaultItem = NO;
            [_arrDataSourc replaceObjectAtIndex:idx withObject:model];
        }];
    }
}

- (void)detailAction:(UIButton *)btn{
    int index = (int)btn.tag-1;
    [self.delegate deletePhoto:index];
    [_arrDataSourc removeObjectAtIndex:index];
    __block BOOL haveDefaultItam;
    [_arrDataSourc enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ImageSelectModel *model = obj;
        if (model.defaultItem == YES) {
            haveDefaultItam = YES;
        }
    }];
    if (!haveDefaultItam) {
        ImageSelectModel *model = [[ImageSelectModel alloc] init];
        model.imageShow = [UIImage imageNamed:@"icon_addimage"];
        model.defaultItem = YES;
        model.delectStart = NO;
        [_arrDataSourc insertObject:model atIndex:_arrDataSourc.count];
    }
    [_mainCollect reloadData];
}

- (void)addDefaultModel{
    ImageSelectModel *model = [[ImageSelectModel alloc] init];
    model.imageShow = [UIImage imageNamed:@"icon_addimage"];
    model.defaultItem = YES;
    model.delectStart = NO;
    [_arrDataSourc addObject:model];
}

@end
